package com.idopartx.phonelightning.utils

import android.content.Context
import android.hardware.Camera
import android.hardware.camera2.CameraManager
import android.os.Build

class LightningUtils {

    companion object {

        fun get(): LightningUtils = Holder.instance

    }

    private object Holder {

        val instance = LightningUtils()

    }

    private var isFlashOn = false

    fun toggle(context: Context) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            val camManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager

            val cameraId = camManager.cameraIdList[0]

            camManager.setTorchMode(cameraId, !isFlashOn)

            isFlashOn = !isFlashOn

        } else {
            var camera = Camera.open()

            var parameters = camera.parameters

            if (isFlashOn) {

                parameters.flashMode = Camera.Parameters.FLASH_MODE_OFF

            } else {

                parameters.flashMode = Camera.Parameters.FLASH_MODE_TORCH

            }

            isFlashOn = !isFlashOn

            camera.parameters = parameters

        }

    }

}